package com.foreverwin.mes.lims.controller;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.model.BadEntryOfWorkshopMate;
import com.foreverwin.mes.lims.model.DefeRecodesOfWorkInProc;
import com.foreverwin.mes.lims.service.BadEntryOfWorkshopMateService;
import com.foreverwin.mes.lims.util.NowString;
import com.sap.me.extension.Services;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.frame.transitionutils.Exceptions;
import com.sap.me.inventory.*;
import com.sap.me.nonconformance.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Mark
 * @since 2020-03-08
 */
@Controller
@RequestMapping("/badEntryOfWorkshopMates")
public class BadEntryOfWorkshopMateController {
    private final Logger logger = LoggerFactory.getLogger(BadEntryOfWorkshopMateController.class);
    private final Boolean isLocalTest = false; //是否在本地测试（若为true，返回自定义数据）


    @Autowired
    public BadEntryOfWorkshopMateService badEntryOfWorkshopMateService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getBadEntryOfWorkshopMateById(@PathVariable String id) {
        BadEntryOfWorkshopMate result;
        try {
            result = badEntryOfWorkshopMateService.selectById(id);
        } catch (Exception e) {
            logger.error("getBadEntryOfWorkshopMateById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getBadEntryOfWorkshopMateList(BadEntryOfWorkshopMate badEntryOfWorkshopMate){
        List<BadEntryOfWorkshopMate> result;
        try {
            EntityWrapper<BadEntryOfWorkshopMate> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(badEntryOfWorkshopMate);
            result = badEntryOfWorkshopMateService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getBadEntryOfWorkshopMateList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getBadEntryOfWorkshopMatePageList")
    public AjaxResult getBadEntryOfWorkshopMatePageList(FrontPage<BadEntryOfWorkshopMate> frontPage, BadEntryOfWorkshopMate badEntryOfWorkshopMate){
        Page result;
        try {
            String site = CommonMethods.getSite();
            badEntryOfWorkshopMate.setSite(site);
            EntityWrapper<BadEntryOfWorkshopMate> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(badEntryOfWorkshopMate);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("warehouse", frontPage.getGlobalQuery())
                    .or().like("inventoryBatch", frontPage.getGlobalQuery())
                    .or().like("itemNo", frontPage.getGlobalQuery())
                    .or().like("itemDesc", frontPage.getGlobalQuery())
                    .or().like("defectCode", frontPage.getGlobalQuery())
                    .or().like("defectDesc", frontPage.getGlobalQuery())
                    .or().like("defectNotes", frontPage.getGlobalQuery())
                    .or().like("determineResult", frontPage.getGlobalQuery())
                    .or().like("determineRemark", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = badEntryOfWorkshopMateService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getBadEntryOfWorkshopMatePageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param badEntryOfWorkshopMate  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult badEntryOfWorkshopMateSave(@RequestBody BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count;
        try {
            count = badEntryOfWorkshopMateService.insertOrUpdate(badEntryOfWorkshopMate) ? 1 : 0;
        } catch (Exception e) {
            logger.error("badEntryOfWorkshopMateSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : badEntryOfWorkshopMate);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult badEntryOfWorkshopMateDelete(@PathVariable("id") String id){
        int count;
        try {
            count = badEntryOfWorkshopMateService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("badEntryOfWorkshopMateDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = badEntryOfWorkshopMateService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("badEntryOfWorkshopMateBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 查询：库存批次、物料编号、物料描述、库存数量
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getInventoryBatch")
    public AjaxResult getInventoryBatch( BadEntryOfWorkshopMate badEntryOfWorkshopMate){
        badEntryOfWorkshopMate.setSite(CommonMethods.getSite());
        List<BadEntryOfWorkshopMate> result =badEntryOfWorkshopMateService.selectInventoryBatch(badEntryOfWorkshopMate);
        //-----------------------------------------------------------------------------------------------------------
        return AjaxResult.success(result);
    }

    /**
     * （库存不良录入）查询：不良代码
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getNCCode")
    public AjaxResult getNCCode(DefeRecodesOfWorkInProc defeRecodesOfWorkInProc) throws BusinessException {
        ArrayList<DefeRecodesOfWorkInProc> result = new ArrayList<DefeRecodesOfWorkInProc>();
        //----------------本地测试Start-----------------------------------------------------------------------------------------------
        if( isLocalTest ) {
            for (int i = 0; i < 4; i++) {
                DefeRecodesOfWorkInProc defeRecodesOfWorkInProcIns = new DefeRecodesOfWorkInProc();
                defeRecodesOfWorkInProcIns.setDefectCode("WG01-NG" + i);
                defeRecodesOfWorkInProcIns.setDefectDesc("外观不良" + i);
                result.add(defeRecodesOfWorkInProcIns);
            }
            return AjaxResult.success(result);
        }
        //----------------本地测试End-----------------------------------------------------------------------------------------------
        String site = CommonMethods.getSite();
        NCProductionServiceInterface ncProductionService = Services.getService("com.sap.me.nonconformance", "NCProductionService", site);
        FindValidNCGroupsAndCodesRequest findValidNCGroupsAndCodesRequest = new FindValidNCGroupsAndCodesRequest();
        FindValidNCGroupsAndCodesResponse findValidNCGroupsAndCodesResponse = ncProductionService.findValidNCGroupsAndCodes(findValidNCGroupsAndCodesRequest);
        List<NCGroupAndCodesSummary> ncGroupsAndCodesL = findValidNCGroupsAndCodesResponse.getNcGroupsAndCodes();
        for (int i = 0; i < ncGroupsAndCodesL.size(); i++) {
            NCGroupAndCodesSummary ncGroupAndCodes = ncGroupsAndCodesL.get(i);
            List<ValidNCCodeSummary> ncCodeL = ncGroupAndCodes.getNcCodes();
            for (int j = 0; j < ncCodeL.size(); j++) {
                ValidNCCodeSummary ncCodeSummary = ncCodeL.get(j);
                DefeRecodesOfWorkInProc defeRecodesOfWorkInProcIns = new DefeRecodesOfWorkInProc();
                defeRecodesOfWorkInProcIns.setDefectCode(ncCodeSummary.getName());
                defeRecodesOfWorkInProcIns.setDefectDesc(ncCodeSummary.getDescription());
                result.add(defeRecodesOfWorkInProcIns);
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * （库存不良判定）查询：库存批次、物料编号、物料描述、库存数量、不良代码、不良描述、发现数量、不良备注
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getInventoryBatchForDetermine")
    public AjaxResult getInventoryBatchForDetermine(BadEntryOfWorkshopMate badEntryOfWorkshopMate){
        List<BadEntryOfWorkshopMate> result;
        badEntryOfWorkshopMate.setSite(CommonMethods.getSite());
        try {
            EntityWrapper<BadEntryOfWorkshopMate> entityWrapper = new EntityWrapper<>();
            entityWrapper.setEntity(badEntryOfWorkshopMate);
            entityWrapper
                    .isNull(DefeRecodesOfWorkInProc.DETERMINE_RESULT);
            result = badEntryOfWorkshopMateService.selectList(entityWrapper);
        } catch (Exception e) {
            logger.error("getInventoryBatchForDetermine -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 库存不良录入保存和修改
     * @param badEntryOfWorkshopMate  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/saveForEntry")
    public AjaxResult saveForEntry(@RequestBody BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        int count;
        try {
            String site = CommonMethods.getSite();
            String user = CommonMethods.getUser();
            Date nowTime = new Date();
            //------------------本地测试数据开始------------------------------------------------------------------------------------
            if(isLocalTest) {
                user = "mark";
            }
            //------------------本地测试数据结束------------------------------------------------------------------------------------
            List<BadEntryOfWorkshopMate> unDetermineList;
            BadEntryOfWorkshopMate conditionIns = new BadEntryOfWorkshopMate();
            String warehouse = badEntryOfWorkshopMate.getWarehouse();
            String inventoryBatch = badEntryOfWorkshopMate.getInventoryBatch();
            conditionIns.setWarehouse(warehouse);
            conditionIns.setInventoryBatch(inventoryBatch);
            //------------------------------------------------------------------------------------------------------------
            EntityWrapper<BadEntryOfWorkshopMate> entityWrapper = new EntityWrapper<>();
            entityWrapper.setEntity(conditionIns);
            entityWrapper.isNull(DefeRecodesOfWorkInProc.DETERMINE_RESULT);
            unDetermineList = badEntryOfWorkshopMateService.selectList(entityWrapper);

            if( unDetermineList!=null && unDetermineList.size()>0 ){
                return AjaxResult.error( "该库存已录入不良信息，不可多次录入" );
            }else{
                String handle = StringUtils.createQUID();
                badEntryOfWorkshopMate.setHandle(handle);
                badEntryOfWorkshopMate.setSite(site);
                badEntryOfWorkshopMate.setCreator(user);
                badEntryOfWorkshopMate.setUpdater(user);
                badEntryOfWorkshopMate.setCreatedDateTime(nowTime);
                badEntryOfWorkshopMate.setModifiedDateTime(nowTime);
                count = badEntryOfWorkshopMateService.saveWithStockScrapping(badEntryOfWorkshopMate,isLocalTest) ? 1 : 0;
            }
        } catch (Exception e) {
            logger.error("BadEntryOfWorkshopMate-saveForEntry -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : badEntryOfWorkshopMate);
    }

    /**
     * 库存不良判定保存和修改
     * @param badEntryOfWorkshopMate  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/saveForDetermine")
    public AjaxResult saveForDetermine(@RequestBody BadEntryOfWorkshopMate badEntryOfWorkshopMate) {
        int count;
        try {
            String site = CommonMethods.getSite();
            String user = CommonMethods.getUser();
            Date nowTime = new Date();
            //------------------本地测试数据开始------------------------------------------------------------------------------------
            if(isLocalTest) {
                user = "mark";
            }
            //------------------本地测试数据结束------------------------------------------------------------------------------------
            badEntryOfWorkshopMate.setSite(site);
            badEntryOfWorkshopMate.setUpdater(user);
            badEntryOfWorkshopMate.setModifiedDateTime(nowTime);
            BadEntryOfWorkshopMate oldIns = badEntryOfWorkshopMateService.selectByHandle(badEntryOfWorkshopMate.getHandle());
            if( oldIns.getDetermineResult()!=null && !"".equalsIgnoreCase(oldIns.getDetermineResult())){
                return AjaxResult.error( "批次"+oldIns.getInventoryBatch()+"没有需要判定的不良信息!" );
            }
            count = badEntryOfWorkshopMateService.saveWithStockScrapping(badEntryOfWorkshopMate,isLocalTest) ? 1 : 0;
        } catch (Exception e) {
            logger.error("BadEntryOfWorkshopMate-saveForDetermine -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : badEntryOfWorkshopMate);
    }
}